#R version 4.4.3 (2025-02-28 ucrt)
#Platform: x86_64-w64-mingw32/x64 (64-bit)
#Running under: Windows 11 x64 

library(dplyr) #1.1.4
library(ggplot2) #3.5.1
library(readr) #2.1.5
library(haven) #2.5.4
library(estimatr) #1.0.6
library(broom.mixed) #0.2.9.6
library(lme4) #1.1-37
library(countrycode) #1.6.1
library(forcats) #1.0.0

`%notin%` <- function(x,y) !(x %in% y) 

setwd("C:/Users/selfd/Documents/autopartyinstitutionalization/legacy/cps/replication")

df1 <- read_csv("data/gwf_panel.csv") |>  
  dplyr::select(countryname, year, v2xps_party, v2x_polyarchy, gwf_duration, gwf_regime, gwf_prior, prior_pi, pi1, pi2, pi3, pi4, asp_dummy, ruling, lgdp, gwf_pduration, gwf_number, fsu, ussr_sat, regime_elecs, av_dm) |>  
  mutate(ccode = countrycode(countryname, origin = "country.name", destination = "cown"), 
         reactive = case_when(ruling == 1 ~ 0, ruling == 0 ~ 1)) |> 
  mutate_at(vars(pi1, pi2, pi3, pi4), ~ifelse(gwf_prior %in% c("Personal", "Military", "Party", "Monarchy") & is.nan(.) | gwf_prior %in% c("Personal", "Military", "Party", "Monarchy") & is.na(.), 0, .)) |>  
  filter(gwf_prior %in% c("Party", "Military", "Personal") & gwf_regime == "democracy") |>  
  mutate(asp_dummy = ifelse(is.na(asp_dummy), 0, asp_dummy)) |>  
  mutate(gwf_prior = factor(gwf_prior, levels = c("Party", "Personal", "Military"))) |>  
  mutate(elections = ifelse(regime_elecs >= 3, "Third-plus", regime_elecs),  elections = recode(elections, `0` = "None", `1` = "First", `2` = "Second"), 
         elections = factor(elections, levels = c("None", "First", "Second", "Third-plus"))) 

#figure 3.1----
# Create the histogram for df2$pi1, but do not display it
marginal_histogram <- ggplot(df1, aes(x = pi1)) +
  geom_histogram(binwidth = 0.1, fill = "grey", color = "black", alpha = 0.5) +
  theme_void()  # No axes or labels for the histogram

# Convert histogram to a grob (graphical object)
marginal_grob <- ggplotGrob(marginal_histogram)

df2 <- read_dta("data/stata/margins3.1.dta")

p <- ggplot(df2) +
  geom_smooth(aes(x = `_at3`, y = `_margin`), method = lm, color = "black", linewidth = 0.75) +
  geom_ribbon(aes(x = `_at3`, y = `_margin`, ymin = `_ci_lb`, ymax = `_ci_ub`), fill = "darkgrey", alpha = 0.2) + # confidence ribbon
  geom_hline(yintercept = 0, linetype = "dashed") +
  theme_bw() +
  ylab("Marginal Effect of a Reactive ASP on \n Party Institutionalization") +
  xlab("Incumbent PI") +
  ggtitle("All Years Pooled") +
  theme(plot.title = element_text(hjust = 0.5), axis.title = element_text(size=10, face = "bold")) +  
  ylim(-0.4, 0.6)

p + annotation_custom(
  grob = marginal_grob,
  xmin = -Inf, xmax = Inf,  # Horizontal span (full range)
  ymin = -0.4, ymax = -0.2    # Adjust the vertical range for positioning and sizing
) + theme(plot.margin = margin(t = 10)) 

#save to file
#ggsave(filename = "C:/Users/selfd/Documents/autopartyinstitutionalization/legacy/plots/fig3_1.jpg", dpi = 500, width = 5, height = 5)

#figure 3.2----
df2 <- read_dta("data/stata/margins3.2.dta") |> 
  mutate(reactive = as.factor(`_at2`))

ggplot(df2, aes(x = reactive, y = `_margin`)) +
  geom_pointrange(aes(ymin = `_ci_lb`, ymax = `_ci_ub`)) +
  ylim(-0.4, 0.6) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  theme_bw() +
  ylab("Marginal Effect of Incumbent PI on \n Party Institutionalization") +
  xlab("Reactive ASP") +
  ggtitle("All Years Pooled") +
  theme(plot.title = element_text(hjust = 0.5), axis.title = element_text(size=10, face = "bold"))

#save to file
#ggsave(filename = "C:/Users/selfd/Documents/autopartyinstitutionalization/legacy/plots/fig3_2.jpg", dpi = 500, width = 5, height = 5)